# 需求：爬取58二手房中的房源信息


import requests
from lxml import etree

if __name__ == '__main__':
    # 爬取到页面源码数据
    url = 'https://cd.58.com/ershoufang/'
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.3'}
    page_text = requests.get(url=url, headers=headers).text
    #数据解析
    tree = etree.HTML(page_text)
    li_list= tree.xpath('//ul[@class="house-list-wrap"]/li')
    with open('58.txt','w',encoding='utf-8') as fp:
        for li in li_list:
            #局部解析需要加上./
            title=li.xpath('./div[2]/h2/a/text()')[0]
            print(title)
            fp.write(title+'\n')